

package com.amiba.crm.admin.common.exception;

import com.amiba.crm.admin.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.UnexpectedTypeException;
import java.util.List;

/**
 * @author HZI.HUI
 * @date 2019/2/1
 * 全局的的异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	/**
	 * 全局异常.
	 *
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R exception(Exception e) {
		return new R<>(e);
	}

	/**
	 * 自定义异常
	 */
	@ExceptionHandler(OperationException.class)
	public R OperationException(OperationException e){
		R r = new R();
		r.setCode(e.getCode());
		r.setMsg(e.getMessage());
		return r;
	}


	/**
	 * 空指针异常
	 * @return
	 */
	@ExceptionHandler(NullPointerException.class)
	public R nullPointerException(OperationException e){
		R r = new R();
		r.setCode(e.getCode());
		r.setMsg("参数不正确");
		return r;
	}

	/**
	 * validation Exception
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler(value = {MethodArgumentNotValidException.class, UnexpectedTypeException.class, BindException.class})
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
		List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
		R result = new R();
		result.setMsg(fieldErrors.get(0).getDefaultMessage());
		log.warn(fieldErrors.get(0).getDefaultMessage());
		return result;
	}

}
